package com.example.springboot.controller;

import com.example.springboot.entity.Course;
import com.example.springboot.service.impl.CourseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wuning at 2018/8/22 15:16
 **/

@RestController
@RequestMapping("/api/course")
public class CourseController {
    @Autowired
    private CourseServiceImpl courseService;


    @RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
    public Course getCourseById (@PathVariable(value = "id") Integer id){
        Course course = courseService.getEntityById(id);
        return course;
    }


    @RequestMapping("/list")
    public List<Course> getCourses(){

        return courseService.getEntityList();
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String, String> add (@RequestBody Course course){
        Map<String, String> map = new HashMap<>();

        try {
            int orderId = courseService.add(course);
            response(map, orderId);
        } catch (Exception e) {
            error(map);

            e.printStackTrace();
        }

        return map;
    }


    /**
     * 根据id删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public Map<String, String> delete (@PathVariable(value = "id") Integer id){
        Map<String, String> map = new HashMap<>();
        try {
            int ret = courseService.delete(id);
            response(map, ret);
        } catch (Exception e) {
            error(map);

            e.printStackTrace();
        }
        return map;
    }


    /**
     * 根据id修改信息
     * @param course
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public Map<String, String> update (@PathVariable("id") Integer id, @RequestBody Course course){
        Map<String, String> map = new HashMap<>();
        try {
            int ret = courseService.update(id, course);
            response(map, ret);
        } catch (Exception e) {
            error(map);

            e.printStackTrace();
        }
        return map;
    }


    private void error(Map<String, String> map) {
        map.put("result", "Error");
        map.put("code", "1");
    }



    private void response(Map<String, String> map, int result) {
        if (result <= 0) {
            error(map);
        } else {
            map.put("result", "OK");
            map.put("code", "0");
        }
    }
}
